package com.zjs.vueUser.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjs.config.JwtConfig;
import com.zjs.config.Result;
import com.zjs.vueUser.entity.User;
import com.zjs.vueUser.entity.UserQuery;
import com.zjs.vueUser.entity.UserRole;
import com.zjs.vueUser.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zjs
 * @since 2020-07-04
 * jwt:  https://blog.csdn.net/akiranicky/article/details/99307713
 * 为什么项目重启后，带着之前的token还可以访问到需要info等需要token验证的接口？
 * 答案：只要不过期，会一直存在，类似于redis
 */
@RestController
@RequestMapping("/vueUser/user")
public class UserController {
    @Resource
    private JwtConfig jwtConfig;

    @Autowired
    private UserService userService;

    @ApiOperation("用户登陆")
    @GetMapping("/login")
    public Result<?> userLogin(User user) {
        if (userService.userLogin(user) == null) {
            return Result.error("账号密码有误");
        }
        JSONObject json = new JSONObject();
        String token = jwtConfig.createToken(user.getUsername());
        if (!StringUtils.isEmpty(token)) {
            json.put("token", token);
        }
        return Result.ok(json);
    }


    @GetMapping("/getUserById")
    public Result<?> getUserById(Long id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    /**
     * 根据请求头的token获取userId
     *
     * @param
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(HttpServletRequest request) {
        String usernameFromToken = jwtConfig.getUsernameFromToken(request.getHeader("Authorization"));
        return Result.ok(usernameFromToken);
    }

    @ApiOperation("获取所有用户")
    @GetMapping("/list")
    public Result<?> userList(HttpServletRequest request, UserQuery query) {

        String token = request.getHeader("Authorization");
        System.out.println("***token***:" + token);
        String usernameFromToken1 = jwtConfig.getUsernameFromToken(request.getHeader("Authorization"));
        System.out.println("****username:" + usernameFromToken1);
        IPage<User> list = userService.userLlst(query);
        return Result.ok(list);
    }

    @PostMapping("/updateState")
    public Result<?> updateState(HttpServletRequest request, User user) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(User::getId, user.getId());
        User param = new User();
        param.setState(user.getState());
        userService.update(param, wrapper);
        return Result.ok();
    }

    /**
     * 新增与更新
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public Result<?> addUser(HttpServletRequest request, User user) {
        if(user.getId() == null){
            int count= userService.count(new QueryWrapper<User>().lambda().eq(User::getUsername, user.getUsername()));
            if(count > 0){
                return Result.error("已存在该用户名(账号)");
            }
        }
        userService.saveOrUpdate(user);
        return Result.ok("操作成功");
    }

    @PostMapping("/deleteUser")
    public Result<?> deleteUser(HttpServletRequest request,@RequestParam Long id) {
        userService.removeById(id);
        return Result.ok("操作成功");
    }


    @GetMapping("/getRoleId")
    public Result<?> getRoleId(Long id) {
        UserRole userRole = userService.getRoleId(id);
        return Result.ok(userRole);
    }

    @PostMapping("/saveOrUpdateRoleUser")
    public Result<?> saveOrUpdate(UserRole role) {
        userService.saveOrUpdateRoleUser(role);
        return Result.ok("操作成功");
    }
}

